import { defineStore } from 'pinia'
import { getDictDataByType, refreshDictCache } from '@/api/dict'
import { setDictCache, getDictCache, clearDictCache } from '@/utils/dict'

// 默认字典数据
const defaultDictMap = {
  sys_normal_disable: [
    { label: '正常', value: '0', elTagType: 'success' },
    { label: '停用', value: '1', elTagType: 'danger' }
  ],
  sys_user_sex: [
    { label: '男', value: '0', elTagType: '' },
    { label: '女', value: '1', elTagType: 'danger' },
    { label: '未知', value: '2', elTagType: 'info' }
  ],
  sys_show_hide: [
    { label: '显示', value: '0', elTagType: 'success' },
    { label: '隐藏', value: '1', elTagType: 'info' }
  ],
  sys_yes_no: [
    { label: '是', value: 'Y', elTagType: 'success' },
    { label: '否', value: 'N', elTagType: 'danger' }
  ],
  sys_menu_type: [
    { label: '目录', value: 'M', elTagType: 'warning' },
    { label: '菜单', value: 'C', elTagType: 'success' },
    { label: '按钮', value: 'F', elTagType: 'info' }
  ],
  sys_config_type: [
    { label: '字符串', value: 'string', elTagType: 'success' },
    { label: '数字', value: 'number', elTagType: 'primary' },
    { label: '布尔值', value: 'boolean', elTagType: 'info' },
    { label: 'JSON', value: 'json', elTagType: 'warning' }
  ]
}

export const useDictStore = defineStore('dict', {
  state: () => ({
    // 字典缓存
    dict: {},
    // 正在获取字典的请求标记
    isFetching: {}
  }),
  
  actions: {
    /**
     * 获取字典
     * @param {string} dictType 字典类型
     * @returns {Promise<Array>} 字典数据
     */
    async getDict(dictType) {
      // 检查默认字典
      if (defaultDictMap[dictType]) {
        return defaultDictMap[dictType]
      }
      
      // 先从缓存获取
      let dictData = getDictCache(dictType)
      
      if (dictData) {
        return dictData
      }
      
      // 如果正在获取该字典，则等待该请求完成
      if (this.isFetching[dictType]) {
        return this.isFetching[dictType]
      }
      
      // 远程获取
      try {
        // 记录正在进行的请求
        this.isFetching[dictType] = getDictDataByType(dictType).then(res => {
          dictData = res.data || []
          // 设置缓存
          setDictCache(dictType, dictData)
          // 清除请求标记
          delete this.isFetching[dictType]
          return dictData
        }).catch(error => {
          console.error(`获取字典数据[${dictType}]失败:`, error)
          // 清除请求标记
          delete this.isFetching[dictType]
          return []
        })
        
        return this.isFetching[dictType]
      } catch (error) {
        console.error(`获取字典数据[${dictType}]失败:`, error)
        return []
      }
    },
    
    /**
     * 获取多个字典
     * @param {Array<string>} dictTypes 字典类型数组
     * @returns {Promise<Object>} 字典对象
     */
    async getDicts(dictTypes) {
      const result = {}
      
      const tasks = dictTypes.map(async dictType => {
        const dictData = await this.getDict(dictType)
        result[dictType] = dictData
      })
      
      await Promise.all(tasks)
      
      return result
    },
    
    /**
     * 刷新字典缓存
     * @param {string} [dictType] 字典类型，不传则刷新全部
     */
    async refreshDict(dictType) {
      try {
        await refreshDictCache(dictType)
        
        // 清除本地缓存
        clearDictCache(dictType)
        
        return true
      } catch (error) {
        console.error('刷新字典缓存失败', error)
        return false
      }
    }
  }
}) 